package com.health.system.common.handler;

import com.health.system.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 全局异常处理
 *
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> globalExceptionHandler(Exception e) {
        log.error("系统内部异常，异常信息：", e);
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> validException(ConstraintViolationException e) {
        log.error("校检失败, 异常信息:", e);
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> validException(BindException e) {
        log.error("校检参数类型为Content-Type:multipart/form-data失败, 异常信息: ", e);

        return Result.fail(buildValidResponse(e.getBindingResult()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> validException(MethodArgumentNotValidException e) {
        log.error("校检参数类型为Content-Type:application/json失败, 异常信息: ", e);

        return Result.fail(buildValidResponse(e.getBindingResult()));
    }

    private String buildValidResponse(BindingResult result) {
        StringBuilder sb = new StringBuilder();

        List<FieldError> fields = result.getFieldErrors();
        for (int i = 0; i < fields.size(); i++) {
            FieldError error = fields.get(i);
            sb.append(error.getField()).append(error.getDefaultMessage());
            if (i != fields.size() - 1) {
                sb.append(", ");
            }
        }

        return sb.toString();
    }

}
